<template>
  <view class="factory-recruitment">
    <view class="post-form">
      <view class="form-group" v-if="false">
        <text class="label">招聘类型 <text class="required">*</text></text>
        <view class="radio-group">
          <!-- 普通招聘选项 -->
          <label class="radio-item" @click="recruitmentType = 0">
            <view class="radio-inner">
              <view
                class="radio-circle"
                :class="{ checked: recruitmentType === 0 }"
              >
                <view class="radio-dot" v-if="recruitmentType === 0"></view>
              </view>
              <text class="radio-text">普通招聘</text>
            </view>
          </label>

          <!-- 特殊招聘选项 -->
          <label class="radio-item" @click="recruitmentType = 1">
            <view class="radio-inner">
              <view
                class="radio-circle"
                :class="{ checked: recruitmentType === 1 }"
              >
                <view class="radio-dot" v-if="recruitmentType === 1"></view>
              </view>
              <text class="radio-text">特殊招聘</text>
            </view>
          </label>
        </view>
        <text v-if="formErrors.recruitType" class="error-text">{{
          formErrors.recruitType
        }}</text>
      </view>
      <view class="form-group">
        <text class="label">职位名称 <text class="required">*</text></text>
        <input
          type="text"
          v-model="formData.positionName"
          class="input"
          :class="{ 'error-border': formErrors.positionName }"
          placeholder="例如：SMT技术员"
        />
        <text v-if="formErrors.positionName" class="error-text">{{
          formErrors.positionName
        }}</text>
      </view>

      <!-- 职位类型输入框 -->
      <view class="form-group">
        <text class="label">职位类型</text>
        <view
          class="picker-input"
          :class="{ 'error-border': formErrors.type }"
          @click="showTypePicker = true"
        >
          <text class="picker-text">{{ pickerTitle || "请选择职位类型" }}</text>
        </view>
        <text v-if="formErrors.type" class="error-text">{{
          formErrors.type
        }}</text>
      </view>

      <view class="form-group">
        <text class="label">公司名称 <text class="required">*</text></text>
        <input
          type="text"
          v-model="formData.corporateName"
          class="input"
          :class="{ 'error-border': formErrors.corporateName }"
          placeholder="例如：中芯科技制造厂"
        />
        <text v-if="formErrors.corporateName" class="error-text">{{
          formErrors.corporateName
        }}</text>
      </view>

      <view class="form-group">
        <text class="label">工作地点 <text class="required">*</text></text>
        <input
          type="text"
          v-model="formData.location"
          class="input"
          :class="{ 'error-border': formErrors.location }"
          placeholder="例如：松江区"
        />
        <text v-if="formErrors.location" class="error-text">{{
          formErrors.location
        }}</text>
      </view>

      <view class="form-group">
        <text class="label">经验要求 <text class="required">*</text></text>
        <input
          type="text"
          v-model="formData.experience"
          class="input"
          :class="{ 'error-border': formErrors.experience }"
          placeholder="例如：2年以上经验"
        />
        <text v-if="formErrors.experience" class="error-text">{{
          formErrors.experience
        }}</text>
      </view>

      <view class="form-group">
        <text class="label">薪资范围 <text class="required">*</text></text>
        <view class="salary-input flex items-center">
          <input
            type="number"
            v-model="formData.salaryMin"
            class="input flex-1"
            :class="{
              'error-border': formErrors.salaryMin || formErrors.salaryRange,
            }"
            placeholder="最低薪资"
          />
          <text class="mx-[24rpx] text-[24rpx]">至</text>
          <input
            type="number"
            v-model="formData.salaryMax"
            class="input flex-1"
            :class="{
              'error-border': formErrors.salaryMax || formErrors.salaryRange,
            }"
            placeholder="最高薪资"
          />
          <text class="ml-[24rpx] text-[24rpx]">/月</text>
        </view>
        <text v-if="formErrors.salaryMin" class="error-text">{{
          formErrors.salaryMin
        }}</text>
        <text v-if="formErrors.salaryMax" class="error-text">{{
          formErrors.salaryMax
        }}</text>
        <text v-if="formErrors.salaryRange" class="error-text">{{
          formErrors.salaryRange
        }}</text>
      </view>

      <view class="mb-[40rpx]">
        <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
          >职位标签</text
        >

        <!-- 添加技能 -->
        <view class="flex mb-[24rpx]">
          <nut-input
            v-model="newSkill"
            placeholder="输入标签后点击添加"
            class="flex-1 rounded-l-[15rpx] border-2 border-gray-200 p-[20rpx] text-[28rpx] bg-gray-50"
            @keypress="onSkillKeyPress"
          />
          <nut-button
            type="primary"
            class="rounded-r-[15rpx] text-[28rpx] bg-blue-600 border-none h-[84rpx] px-[30rpx]"
            @click="addSkill"
          >
            添加
          </nut-button>
        </view>

        <!-- 显示标签 -->
        <view class="flex flex-wrap gap-[16rpx]">
          <view
            v-for="(tag, index) in tags"
            :key="index"
            class="flex items-center bg-blue-50 text-blue-600 px-[20rpx] py-[12rpx] rounded-[30rpx] text-[26rpx] border border-blue-100"
          >
            <text>{{ tag }}</text>
            <IconFont
              name="close"
              size="10"
              class="ml-[12rpx] text-[24rpx] text-blue-400 cursor-pointer"
              @click="removeSkill(index)"
            />
          </view>
        </view>
      </view>

      <view class="form-group">
        <text class="label">职位描述 <text class="required">*</text></text>
        <nut-textarea
          v-model="formData.description"
          class="textarea"
          :class="{ 'error-border': formErrors.description }"
          placeholder="请输入职位描述..."
        />
        <text v-if="formErrors.description" class="error-text">{{
          formErrors.description
        }}</text>
      </view>


      <!-- 区域选择 -->
      <RegionSelector 
        v-model="regionLevel"
        @change="handleRegionChange"
      />

      <nut-button class="submit-btn" @click="submitForm">发布招聘</nut-button>
    </view>
    <!-- 职位类型选择器弹窗 -->
    <nut-popup v-model:visible="showTypePicker" position="bottom" round>
      <nut-picker
        :columns="jobTypes.map((item) => ({ text: item.type, value: item.id }))"
        :title="pickerTitle"
        @confirm="onTypeConfirm"
        @cancel="showTypePicker = false"
      />
    </nut-popup>

    <!-- 支付方式选择弹窗 -->
    <PaymentMethodModal 
      v-model="showPaymentModal" 
      :amount="parseFloat(fee)"
      @confirm="handlePaymentConfirm"
      @cancel="handlePaymentCancel"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { showToast } from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { post } from "@/utils/request";
import Taro from "@tarojs/taro";
import RegionSelector from '@/components/RegionSelector.vue';
import PaymentMethodModal from '@/components/PaymentMethodModal.vue';
import { useUserStore } from '@/store/user';

export interface JobPost {
  corporateName?: string;
  deadline?: string;
  description?: string;
  experience?: string;
  location?: string;
  positionName?: string;
  salaryMax?: string;
  salaryMin?: string;
  type?: number;
  labels?: string;
  [property: string]: any;
}

// 表单数据
const formData = reactive<JobPost>({});
const recruitmentType = ref(1); // 添加招聘类型字段

/**
 * 区域选择
 * @type {import('vue').Ref<string>}
 */
const regionLevel = ref("city");

// 区域价格
const fee = ref<string>('1'); //默认是区域是市级

// 用户store
const userStore = useUserStore();

// 支付方式选择弹窗相关
const showPaymentModal = ref(false);
const currentTaskId = ref<number | null>(null);
const rangeType = ref<string>('1');

/**
 * 处理区域选择变化
 * @param data 区域选择数据
 */
const handleRegionChange = (data: { value: string; fee: number; range: string }) => {
  fee.value = String(data.fee);
  rangeType.value = data.range;
};

/** 表单数据类型 - 仅保留职位类型相关字段 */
interface JobFormData {
  id: number;
  type: string;
}

/** 职位类型选项 */
// const jobTypes = ["普工", "技工", "管理", "质检", "仓储", "后勤", "其他"];
const jobTypes = ref<JobFormData[]>([]);

/** 职位类型选择器显示状态 */
const showTypePicker = ref(false);
const pickerTitle = ref();

/** 职位类型选择器确认事件 */
function onTypeConfirm(value: any) {
  // 将选择的职位类型赋值给表单
  formData.type = value?.selectedValue[0] || "";
  console.log(formData.type);
  // 更新标题（可选）
  const selectedType = jobTypes.value.find((item) => item.id === formData.type);
  pickerTitle.value = selectedType?.type || "选择职位类型";
  // 关闭弹窗
  showTypePicker.value = false;
}

// 计算属性：根据 id 获取 type 名称
// const typeName = computed(() => {
//   const selectedType = jobTypes.value.find(item => item.id == formData.type);
//   console.log(selectedType?.type)
//   return selectedType?.type || '请选择职位类型';
// })

// 职位标签
const tags = ref([]);

const newSkill = ref([]);
function onSkillKeyPress(e: any) {
  if (e.key === "Enter") {
    addSkill();
  }
}
function addSkill() {
  const skill = newSkill.value.trim();
  if (skill && !tags.value.includes(skill)) {
    tags.value.push(skill);
    newSkill.value = "";
  }
}

function removeSkill(index: number) {
  tags.value.splice(index, 1);
}

// 选中的标签
// const selectedTags = ref<string[]>([]);

// 切换标签选择状态
// const toggleTag = (index: number) => {
//   tags.value[index].selected = !tags.value[index].selected;
//   // 更新选中的标签列表
//   selectedTags.value = tags.value
//     .filter((tag) => tag.selected)
//     .map((tag) => tag.name);
// };

// 表单验证错误信息
const formErrors = reactive<
  Partial<Record<keyof JobPost | "salaryRange", string>>
>({});

// 表单验证方法
const validateForm = (): boolean => {
  const errors: Partial<Record<keyof JobPost | "salaryRange", string>> = {};

  // if (!formData.recruitmentType) {
  //   errors.recruitmentType = "请选择招聘类型";
  // }

  // 职位名称验证
  if (!formData.positionName?.trim()) {
    errors.positionName = "请输入职位名称";
  }

  // 公司名称验证
  if (!formData.corporateName?.trim()) {
    errors.corporateName = "请输入公司名称";
  }

  if (!formData.type) {
    errors.type = "请选择职位类型";
  }

  // 工作地点验证
  if (!formData.location?.trim()) {
    errors.location = "请输入工作地点";
  }

  // 经验要求验证
  if (!formData.experience?.trim()) {
    errors.experience = "请输入经验要求";
  }

  // 最低薪资验证
  if (!formData.salaryMin?.trim()) {
    errors.salaryMin = "请输入最低薪资";
  } else if (isNaN(Number(formData.salaryMin))) {
    errors.salaryMin = "最低薪资必须为数字";
  }

  // 最高薪资验证
  if (!formData.salaryMax?.trim()) {
    errors.salaryMax = "请输入最高薪资";
  } else if (isNaN(Number(formData.salaryMax))) {
    errors.salaryMax = "最高薪资必须为数字";
  }

  // 薪资范围验证（当两者都填写时）
  if (
    formData.salaryMin &&
    formData.salaryMax &&
    !errors.salaryMin &&
    !errors.salaryMax
  ) {
    const min = Number(formData.salaryMin);
    const max = Number(formData.salaryMax);
    if (min >= max) {
      errors.salaryRange = "最低薪资必须小于最高薪资";
    }
  }

  // 职位描述验证
  if (!formData.description?.trim()) {
    errors.description = "请输入职位描述";
  }

  // 更新错误信息
  Object.assign(formErrors, errors);

  // 返回验证结果（无错误则为有效）
  return Object.keys(errors).length === 0;
};

// 提交表单
const submitForm = async () => {
  // 先进行表单验证
  if (!validateForm()) {
    showToast({ title: "请完善必填信息", icon: "none", duration: 2000 });
    return;
  }

  // 显示加载状态
  Taro.showLoading({ title: "发布中..." });

  try {
    // 构建提交数据（包含选中的标签）
    const submitData = {
      ...formData,
      recruitmentType: recruitmentType.value,
      labels: tags.value.join(","),
      range: rangeType.value,
      fee: fee.value
    };
    console.log("====>", submitData);
    console.log("区域选择:", regionLevel.value, "信息费:", fee.value, "范围类型:", rangeType.value);
    // 提交数据到接口
    const res = await post("/recruitment/save", submitData);
    console.log("====>", res);
    if (res.code === 0) {
      Taro.showToast({ title: "发布成功", icon: "success", duration: 2000,
        // 提示框显示完成后执行跳转
        success: () => {
          // 重置表单
          Object.keys(formData).forEach((key) => {
            formData[key as keyof JobPost] = "";
          });
          tags.value = [];

          // 延迟2000ms，确保提示完全显示
          // setTimeout(() => {
          //   Taro.redirectTo({ url: "/pages/post/index" });
          // }, 2000);
          // 显示支付方式选择弹窗
          showPaymentModal.value = true;
          // 保存任务ID用于后续支付
          currentTaskId.value = res.data;
        }
      });
    } else {
      Taro.showToast({ title: res.msg || "发布失败", icon: "none", duration: 2000 });
    }
  } catch (error) {
    Taro.showToast({ title: "网络错误，请稍后重试", icon: "none", duration: 2000 });
  } finally {

  }
};



/**
 * 处理支付方式确认
 * @param method 支付方式
 */
const handlePaymentConfirm = async (method: 'balance' | 'wechat') => {
  if (!currentTaskId.value) {
    Taro.showToast({
      title: "任务ID不存在",
      icon: "none",
    });
    return;
  }

  try {
    // 调用支付接口
    const payRes = await post("/pay/recruitment", {
      amount: fee.value,
      bid: currentTaskId.value,
      vipType: 1,
      deductionBalance: method === 'balance' ? 1 : 0, // 余额支付传1，微信支付传0
    });

    if (payRes.code == 0) {
      if (method === 'wechat') {
        // 微信支付
        doPay(payRes.data);
      } else {
        // 余额支付
        if (payRes.data.code == 2) {
          // 余额支付成功
          Taro.showToast({
            title: "支付成功！",
            icon: "success",
            duration: 2000,
          });
          // 更新用户余额
          const newBalance = (userStore.userInfo.balance || 0) - parseFloat(fee.value);
          userStore.updateBalance(newBalance);
          setTimeout(() => {
            Taro.navigateBack();
          }, 2000);
        } else {
          // 余额支付失败
          Taro.showToast({
            title: payRes.data.msg || "支付失败",
            icon: "error",
            duration: 2000,
          });
        }
      }
    } else {
      Taro.showToast({
        title: "支付失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error('支付失败:', error);
    Taro.showToast({
      title: "支付失败，请重试",
      icon: "none",
    });
  } finally {
    currentTaskId.value = null; // 清空任务ID
  }
};

/**
 * 处理支付取消
 */
const handlePaymentCancel = () => {
  currentTaskId.value = null; // 清空任务ID
  Taro.showToast({
    title: "已取消支付",
    icon: "none",
  });
};

// 支付发布任务费用（保留原函数用于兼容，已废弃）
// const payTask = async (id: number) => {
//   try {
//     const payRes = await post("/pay/recruitment", {
//       amount: fee.value,
//       bid: id,
//       vipType: 1,
//     });
//     if (payRes.code == 0) {
//       doPay(payRes.data);
//       // Taro.showToast({
//       //   title: `任务发布成功！总金额：¥${totalAmount.value}`,
//       //   icon: "success",
//       //   duration: 3000,
//       // });
//     } else {
//       Taro.showToast({
//         title: "支付失败",
//         icon: "none",
//       });
//     }
//   } catch (error) {
//     console.error('支付失败:', error);
//     Taro.showToast({
//       title: "支付失败，请重试",
//       icon: "none",
//     });
//   } finally {
//     // isSubmitting.value = false; // 重置loading状态
//   }
// };

// 微信弹窗
const doPay = (param: any) => {
  (window as any).WeixinJSBridge.invoke(
    "getBrandWCPayRequest",
    {
      appId: param.appid, //公众号ID，由商户传入
      timeStamp: param.timeStamp, //时间戳，自1970年以来的秒数
      nonceStr: param.nonceStr, //随机串
      package: param.prepayId,
      signType: "RSA", //微信签名方式：
      paySign: param.paySign, //微信签名
    },
    function (param: any) {
      if (param.err_msg == "get_brand_wcpay_request:ok") {
        // 使用以上方式判断前端返回,微信团队郑重提示：
        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
        Taro.showToast({
          title: "支付成功！",
          icon: "success",
          duration: 2000,
        });
      } else {
        Taro.showToast({ title: "支付失败！", icon: "error", duration: 2000 });
      }
    }
  );
};


// 招聘类型
const jobRecruitmentType = async () => {
  const res = await post("/dictionary/recruitmentLabel");
  if (res.code == "0") {
    jobTypes.value = res.data.map((item: any) => ({
      id: item.columns.id,
      type: item.columns.name,
    }));
  }
};
jobRecruitmentType();
</script>

<style lang="scss" scoped>
:deep(.region-selector) {
  margin: 0 !important;
  .nut-radio {
    margin-bottom: 0 !important;
  }
}
.post-form {
  background-color: white;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  margin-bottom: 8rpx;
  font-weight: bold;
  color: #555;
  font-size: 28rpx;
}

.required {
  color: #ff4d4f;
}

.input,
.textarea {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

/* 错误状态样式 */
.error-border {
  border-color: #ff4d4f !important;
}

.error-text {
  color: #ff4d4f;
  font-size: 24rpx;
  margin-top: 8rpx;
  display: block;
  line-height: 1.4;
}

.salary-input {
  display: flex;
  align-items: center;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.tag-option {
  background-color: #f0f0f0;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  cursor: pointer;
  font-size: 24rpx;
  transition: all 0.2s;
}

.tag-option.selected {
  background-color: #e3f2fd;
  color: #1976d2;
  border-color: #1976d2;
  border: 1rpx solid;
}

.submit-btn {
  background-color: #1976d2 !important;
  color: white !important;
  width: 100%;
  margin-top: 40rpx;
  padding: 24rpx 40rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
}

.preview {
  margin-top: 40rpx;
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.container {
  width: 750rpx;
  max-width: 100%;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  margin-bottom: 40rpx;
  height: 60rpx;
}

.header h1 {
  color: #333;
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.salary-input span {
  margin: 0 24rpx;
}

.preview-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #eee;
}

.job-card {
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 30rpx;
  position: relative;
}

.job-card::before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 4rpx;
  background-color: #1976d2;
  border-radius: 12rpx 0 0 12rpx;
}

.job-title {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.company-info {
  color: #666;
  font-size: 24rpx;
  margin-bottom: 10rpx;
}

.salary {
  color: #f44336;
  font-size: 32rpx;
  font-weight: bold;
  margin: 20rpx 0;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin: 20rpx 0;
}

.tag {
  background-color: #f5f5f5;
  color: #666;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.footer {
  display: flex;
  justify-content: space-between;
  color: #999;
  font-size: 24rpx;
  margin-top: 20rpx;
}

.apply-btn {
  background-color: #1976d2;
  color: white;
  border: none;
  padding: 10rpx 30rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  cursor: pointer;
}

/* 父容器：确保选项水平排列 */
.radio-group {
  display: flex;         /* 横向排列选项 */
  gap: 60rpx;            /* 选项之间的间距 */
  padding: 10rpx 0;
}

/* 单个选项容器 */
.radio-item {
  cursor: pointer;       /* 手形指针 */
}

/* 核心：包裹单选框和文字的容器 */
.radio-inner {
  display: inline-flex;  /* 强制在同一行 */
  align-items: center;   /* 垂直居中对齐 */
  vertical-align: middle; /* 与其他元素基线对齐 */
}

/* 单选框样式 */
.radio-circle {
  width: 34rpx;
  height: 34rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;        /* 防止被压缩 */
}

/* 选中状态 */
.radio-circle.checked {
  border-color: #1976d2;
  background-color: #e3f2fd;
}

/* 选中圆点 */
.radio-dot {
  width: 18rpx;
  height: 18rpx;
  border-radius: 50%;
  background-color: #1976d2;
}

/* 文字样式 */
.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 16rpx;    /* 与单选框的间距 */
}
/* 输入框聚焦样式 */
input:focus,
textarea:focus {
  outline: none;
  border-color: #1976d2;
}

/* 表单组样式 - 包含职位类型输入框整体布局 */
.form-group {
  margin-bottom: 30rpx;
}

/* 标签样式 - 职位类型文字标签 */
.label {
  display: block;
  margin-bottom: 8rpx;
  font-weight: bold;
  color: #555;
  font-size: 28rpx;
}

/* 选择器输入框样式 - 职位类型点击区域 */
.picker-input {
  display: flex;
  align-items: center;
  min-height: 76rpx;
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: white;
  cursor: pointer;
}

/* 选择器文字样式 - 职位类型显示文字 */
.picker-text {
  color: #333;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 错误提示样式 - 职位类型未选择时的错误文字 */
.error-text {
  color: #f44336;
  font-size: 24rpx;
  margin-top: 8rpx;
  display: block;
}

/* 错误边框样式 - 职位类型未选择时的红色边框 */
.error-border {
  border-color: #f44336 !important;
}

/* 输入框聚焦样式 - 职位类型选择框聚焦效果 */
.picker-input:focus {
  outline: none;
  border-color: #1976d2;
}
/* 去除 nut-textarea 的内边距 */
:deep(.nut-textarea) {
  padding: 20rpx !important; /* 使用 !important 强制覆盖组件默认样式 */
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
}
</style>
